package bainuo

import com.alibaba.fastjson.JSON
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovy.sql.Sql
import wsd.sys.SST

import java.time.Instant

// 程序入口
def execute(data, dlzt) {
    println "-------------------------调用物料档案接口-------------------------"
    // 定义请求地址 应该是在这里开始
    def urlStr = "http://10.1.1.93:9000/bnyy.esb.biz.wms.warehouse.material";
    def ClientId = "bnyy.esb.biz.bip";//ESB平台分配给应用的ID
    def OperationCode = "bnyy.esb.biz.wms.warehouse.material";//ESB平台分配给接口服务操作的编码
    def LoginCode = "sysadmin"; //ESB平台分配给注册应用的用户名
    def LoginPassword = "000000";//ESB平台分配给注册应用的密码
    try {
        //请求信息 校验
        def items = data.get("items")
        // 获取回来是数组，需要循环校验
        items.each { item ->
            def mtrlNo = item.get("mtrlNo")
            def mtrlName = item.get("mtrlName")
            def mtrlSpec = item.get("mtrlSpec")
            def id = item.get("id")
            def unitId = item.get("unitId")
            def mtrlTaxrate = item.get("mtrlTaxrate")
            def mtrlClass = item.get("mtrlClass")
            def nbMtrlName = item.get("nbMtrlName")
            def mtrlCateid = item.get("mtrlCateid")
            def mtrlBrandmark = item.get("mtrlBrandmark")
            def cas = item.get("cas")
            def lowLimitWarningValue = item.get("lowLimitWarningValue")
            def spProperty = item.get("spProperty")
            def dmflag = item.get("dmflag")
            def storageConditions = item.get("storageConditions")
            def fNote = item.get("fNote")
            def formerName = item.get("formerName")
            def creationtime = item.get("creationtime");
            def modifiedtime = item.get("modifiedtime");
            def manufacturerId = item.get("manufacturerId");
            def manufacturer = item.get("manufacturer");

            def corps = item.get("corps")
            corps.each { corp ->
                def ID = corp.get("id")
                def cmtrlAddUnitId = corp.get("cmtrlAddUnitId")
                def cmtrlAddRate = corp.get("cmtrlAddRate")  // 注意：这个字段在 SQL 查询中没有出现
                def defaultFlag = corp.get("defaultFlag")

                if (ID == null) {
                    return ["state": 0, "Ascript": "缺少辅计量子表ID(id) 请求JSON" + data]
                }
                if (cmtrlAddUnitId == null) {
                    return ["state": 0, "Ascript": "缺少辅计量单位(cmtrlAddUnitId) 请求JSON" + data]
                }
                if (cmtrlAddRate == null) {
                    return ["state": 0, "Ascript": "缺少辅助转化率(cmtrlAddRate) 请求JSON" + data]
                }
                if (defaultFlag == null) {
                    return ["state": 0, "Ascript": "是否采购默认单位(defaultFlag) 请求JSON" + data]
                }
                if (mtrlNo == null) {
                    return ["state": 0, "Ascript": "缺少物料代码(mtrlNo) 请求JSON" + data]
                }
                if (mtrlName == null) {
                    return ["state": 0, "Ascript": "缺少物料名称(mtrlName) 请求JSON" + data]
                }
                if (id == null) {
                    return ["state": 0, "Ascript": "缺少主键(id) 请求JSON" + data]
                }
                if (mtrlClass == null) {
                    return ["state": 0, "Ascript": "缺少物料类别(mtrlClass) 请求JSON" + data]
                }
                if (mtrlCateid == null) {
                    return ["state": 0, "Ascript": "缺少物料类别编码(mtrlCateid) 请求JSON" + data]
                }
            }

        }
        def reMap = TransVoucherOpenApi_Create(data, dlzt, ClientId, OperationCode, LoginCode, LoginPassword)
        // 调用接口返回数据
        //reMap = bainuo.HQMHttpUtil.httpFWToMap(urlStr, data,ClientId,OperationCode,LoginCode,LoginPassword);
        return reMap
    } catch (Exception e) {
        e.printStackTrace();
        return ["state": 0, "Ascript": "请求参数错误,请检查"]
    }

}

def TransVoucherOpenApi_Create(data, dlzt, ClientId, OperationCode, LoginCode, LoginPassword) {
    try {
        def bodyUpList = data.get("items")
        if (bodyUpList == null || bodyUpList.size() == 0) {
            return ["state": 0, "Ascript": "请求参数中表体不能为空"]
        }
        def items = [:]
//        def BodyToObject = [ "mtrlNo": "物料代码", "mtrlName": "物料名称", "mtrlSpec": "规格型号","id": "主键", "unitId": "计量单位", "mtrlTaxrate": "税率",
//                             "mtrlClass": "物料类别",  "mtrlCateid": "物料类别ID","mtrlBrandmark": "生产厂商", "cas": "CAS", "lowLimitWarningValue": "库存警戒线","spProperty": "特殊性质",
//                             "dmflag": "是否精麻毒放","storageConditions": "储存条件","fNote": "备注"]
//        def CorpToObject = ["id": "辅计量子表ID", "cmtrlAddUnitId": "辅计量单位", "cmtrlAddRate": "辅助转化率","defaultFlag": "是否采购默认单位"]

//        //表体结构
//        def RDRecordDetails = []
//        //表体参数循环赋值
//        for (int i = 0; i < bodyUpList.size(); i++) {
//            def bodyMap = bodyUpList.get(i)
//            if (bodyMap == null || bodyMap.size() == 0) {
//                return ["state": 0, "Ascript": "表体数据不能为空"]
//            }
//            def item = [:]
//            for (def key : BodyToObject.keySet()) {
//                item.put(key, bodyMap.get(key))
//            }
//            def corpMap = bodyMap.get("corps")
//            def corp = [:]
//            for(def KEY : CorpToObject.keySet()){
//                corp.put(KEY, corpMap.get(KEY))
//            }
//            item.put("corps")
//            RDRecordDetails.add(item)
//        }
//        items.put("items", RDRecordDetails)
        def reMap = HQMHttpUtil.httpFWToMap("http://10.1.1.238:9000/bnyy.esb.biz.wms.material.archives", data, ClientId, OperationCode, LoginCode, LoginPassword, dlzt)
        def state = 1
        def msg = ""
        def code = ""
        def success = ""
        def request = reMap.json
        def returnJSON = ""
        if ("1".equals(reMap.get("state").toString())) {
            returnJSON = reMap.data
            def jsonSlurper = new JsonSlurper()
            def dJSON = jsonSlurper.parseText(returnJSON)
            if ("200".equals(dJSON.code.toString())) {
                state = 1
                success = "成功"
            } else {
                state = 0
                success = "失败"
            }
            code = dJSON.code
            msg = dJSON.message
        } else {
            state = 0
            msg = reMap.msg
            success = "失败"
        }

        def params = [:]
        params.put("code", "'" + code + "'")
        params.put("message", "'" + msg + "'")
        params.put("success", "'" + success + "'")
        params.put("state", state)
        params.put("Ascript", "'" + msg + "'")
        params.put("time", "getdate()")
        params.put("response", "'" + ("调用WMS返回报文=" + returnJSON) + "'") // 添加响应内容

        // 将 data 转换为 JSON 字符串
        def dataStr = JsonOutput.toJson(data)
        params.put("request_data", "'" + dataStr + "'")
        HQMHttpUtil.insertLog(params)
        return ["state": state, "Ascript": msg]
    }

    catch (Exception e) {
        e.printStackTrace();
        return ["state": 0, "Ascript": "操作错误"]
    }

}

class HQMHttpUtil {
    public static HashMap<String, Object> account = new HashMap<String, Object>();

    public HQMHttps() {
    }

    public HQMHttps(HashMap<String, Object> account) {
        this.account = account;
    }

    static def insertLog(params) {
        def conn = null
        try {
            // 创建数据库连接
            conn = Sql.newInstance(SST.hqcon(1))

            // 构建字段名字符串和占位符字符串
            def insertKeys = params.keySet().join(",")
            def placeholders = params.values().collect { "?" }.join(",")

            // 构建插入语句
            def sqlQuery = "INSERT INTO wms_bainuo_log (${insertKeys}) VALUES (${placeholders})"

            // 使用 withStatement 闭包来执行预处理语句
            conn.withStatement { stmt ->
                stmt.execute(sqlQuery, params.values() as List)
            }
        } catch (Exception e) {
            e.printStackTrace()
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    public static Map httpFWToMap(String url, Map mapdata, String clientId, String operationCode, String loginCode, String loginPassword, dlzt) {
        def returnMap = [:]
        String json = JSON.toJSONString(mapdata);
        println "请求JSON"
        println json
        //PrintWriter out = null;
//        DataOutputStream out
        OutputStream out
        BufferedReader ins = null;
        String result = "";

        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
//            conn.setInstanceFollowRedirects(true);
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "Keep-Alive");
//            conn.setRequestProperty("Transfer-Encoding", "chunked");
//            conn.setRequestProperty("Keep-Alive", "chunked");
            conn.setRequestProperty("ClientId", clientId);
            conn.setRequestProperty("OperationCode", operationCode);
            conn.setRequestProperty("LoginCode", loginCode);
            conn.setRequestProperty("LoginPassword", loginPassword);
            conn.connect();
            // 获取HttpURLConnection对象对应的输出流
            //            out = new PrintWriter(conn.getOutputStream());
            //            // 发送请求参数
            //            out.print(json);
            //            // flush输出流的缓冲
            //            out.flush();
            out = conn.getOutputStream();
            if (!"".equals(json)) {
                //out.writeBytes(json);
                out.write(json.getBytes("UTF-8"));
            }
            out.flush();
            out.close();


            // 定义BufferedReader输入流来读取URL的响应
            //            ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            if (conn.getResponseCode() == 200) {
                ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            } else {
                ins = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
            }

            String line;
            while ((line = ins.readLine()) != null) {
                result += line;
            }

            def map = new JsonSlurper().parseText(result)
            def now = Instant.now()

            //String SQL = "insert into bainuo_log (code, message, success, state, Ascript, time) values ("+result.code+", ?, ?, ?, ?, ?)"""


            println("调用WMS返回报文=" + result)
//            return JSON.parseObject(result, Map.class);
            returnMap.put("state", "1")
            returnMap.put("msg", "成功")
            returnMap.put("data", result)
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("[POST请求]向地址：" + url + " 发送数据：" + json + " 发生错误!" + result + "JSON结束");
            returnMap.put("state", "0")
            returnMap.put("msg", "错误：" + e.getMessage())
            returnMap.put("data", result)
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {
                System.out.println("关闭流异常");
            }
        }
        returnMap.put("json", json)
        return returnMap;
    }
}

